import 'dart:convert';

import 'package:dio/dio.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:web_socket_channel/io.dart';
import 'package:web_socket_channel/web_socket_channel.dart';
import 'package:xianyu_school/utils/url.dart';
import 'package:xianyu_school/xianyuApp/entity/conversation/conversation.dart';
import 'package:xianyu_school/xianyuApp/entity/message/messages.dart';
import 'package:xianyu_school/xianyuApp/mine/Widgets/BallPulseIndicator.dart';

class messageDetailPage extends StatefulWidget {
  messageDetailPage({Key key, this.to,this.channel}) : super(key: key);
  WebSocketChannel channel;
  String to;
  String fromimg;
  String toimg;
  @override
  State<StatefulWidget> createState() {
    return _messageDetailPageState();
  }
}

class _messageDetailPageState extends State<messageDetailPage> {
  String from;
  String content;
  TextEditingController _controller;
  WebSocketChannel channel;
  List<messages> ms = [];
  String url = urls().url;
  conversation c;
  var _futureBuilderFuture;

  Future<void> createconversation() async{
    SharedPreferences pres = await SharedPreferences.getInstance();
    from = pres.getString("username");
    Response re = await Dio().get(url+"/users/createC",queryParameters: {"user1":from,"user2":widget.to});
    var responseJson = json.decode(re.data.toString());
    c = conversation.fromJson(responseJson);
    chathis(c.conversationid);
    return re;
  }

  Future<void> chathis(int conversationid) async{
    Response re = await Dio().get(url+"/users/chathis",queryParameters: {"conversationid":conversationid});
    if(re.data.toString()=="No more data") return;
    var responseJson = json.decode(re.data.toString());
    responseJson.forEach((data) {
      setState(() {
        ms.add(messages.fromJson(data));
      });
    });
  }

  void chat(messages m) async{
    Response re = await Dio().post(url+"/users/chat",data: m.toJson());
  }

  @override
  void initState() {
    super.initState();
    connnect();
    _futureBuilderFuture = createconversation();
    _controller = TextEditingController();
  }

  Widget _buidTextcomposer(){
    return Row(
      children: [
        Container(
          margin:EdgeInsets.all(8.0),
          width: 280,
          child: TextField(
            controller: _controller,
          ),
        ),
        IconTheme(
          data: IconThemeData(color: Theme.of(context).accentColor),
          child: Container(
            child: Row(
              children: [
                Container(
                  child: IconButton(
                    icon: Icon(Icons.send),
                    onPressed: (){
                      messages a1 = new messages();
                      a1.fromusername = from;
                      a1.tousername = widget.to;
                      a1.message = _controller.text;
                      a1.conversationid = c.conversationid;
                      setState(() {
                        ms.add(a1);
                      });
                      chat(a1);
                      channel.sink.add("to:"+widget.to+";"+_controller.text);
                    },
                  ),
                )
              ],
            ),
          ),
        )
      ],
    );
  }

  void connnect() async{
    SharedPreferences pres = await SharedPreferences.getInstance();
    from = pres.getString("username");
    channel = IOWebSocketChannel.connect("ws://192.168.1.105:8080/websocket/" + from);
    channel.stream.listen((message1) {
      print(message1);
      List<String> a = message1.split(";");
      messages a1 = new messages();
      a1.fromusername = a[0].split(":")[1];
      a1.tousername = widget.to;
      a1.message = a[1];
      a1.conversationid = c.conversationid;
      setState(() {
        ms.add(a1);
      });
    });
  }
  
  Widget tou(int index){
    if(ms[index].fromusername==c.user1)
      return Image.memory(
        base64.decode(c.user1img),
        fit: BoxFit.fill,
        gaplessPlayback:true,
      );
    else
      return Image.memory(
        base64.decode(c.user2img),
        fit: BoxFit.fill,
        gaplessPlayback:true,
      );
  }
  
  Widget message1(int index){
    if(ms[index].fromusername==from){
      return Row(
        children: [
          Expanded(child: Text(" ")),
          Container(
            height:40,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                border: Border.all(width: 1,color: Colors.grey)
            ),
            child: Center(
              child: Text(
                ms[index].message,
                style: TextStyle(
                    fontSize: 18
                ),
              ),
            ),
          ),
          Container(
            margin: EdgeInsets.fromLTRB(0.0,0.0,10.0,10.0),
            height:50,
            width: 50,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(150),
            ),
            child: tou(index)
          ),
        ],
      );
    }
    else{
      return Row(
        children: [
          Container(
            margin: EdgeInsets.fromLTRB(0.0,0.0,10.0,10.0),
            height:50,
            width: 50,
            decoration: BoxDecoration(
              borderRadius: BorderRadius.circular(150),
            ),
            child: tou(index)
          ),
          Container(
            margin: EdgeInsets.fromLTRB(0.0,0.0,10.0,10.0),
            height:40,
            decoration: BoxDecoration(
                color: Colors.white,
                borderRadius: BorderRadius.all(Radius.circular(4.0)),
                border: Border.all(width: 1,color: Colors.grey)
            ),
            child: Center(
              child: Text(
                ms[index].message,
                style: TextStyle(
                    fontSize: 18
                ),
              ),
            ),
          ),
        ],
      );
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: CupertinoNavigationBar(
        backgroundColor: Colors.yellow,
        middle: Text(widget.to),
      ),
      body:FutureBuilder(
        future: _futureBuilderFuture,
        builder: (context,snapshot){
          if(snapshot.hasData){
            return Container(
              child: Column(
                children: [
                  Flexible(
                      child:ListView.builder(
                        itemBuilder: (BuildContext context, int index) {
                          return message1(index);
                        },
                        itemCount:ms.length,
                      )
                  ),
                  Divider(height: 1.0,),
                  Container(
                    decoration: BoxDecoration(
                        color: Theme.of(context).cardColor
                    ),
                    child: _buidTextcomposer(),
                  )
                ],
              ),
            );
          }
          else return BallPulseIndicator(
              color: Colors.black
          );
        },
      )
    );

    @override
    dispose() {
      super.dispose();
      _controller.dispose();
    }
  }
}